import { query } from '@/lib/db';
import { NextRequest, NextResponse } from 'next/server';

// next创建接口见官网: https://nextjs.org/docs/app/building-your-application/routing/route-handlers
// NextRequest即request见官网: https://nextjs.org/docs/app/api-reference/functions/next-request
// NextResponse即NextResponse.json见官网: https://nextjs.org/docs/app/api-reference/functions/next-response

// get接口,访问http://localhost:3001/api/unit1/test-get
export async function GET(
  request: NextRequest
  // 第二参数为动态路线相关,就是app/items/[slug]/route.js这种, 见官网: https://nextjs.org/docs/app/building-your-application/routing/route-handlers#dynamic-route-segments
  // { params }: { params: { slug: string } }
) {
  // 数据库操作
  const table1 = await query({
    sql: 'SELECT * FROM table1',
    values: [],
  });

  // 服务端发起请求
  let data = {};
  try {
    const res = await fetch('https://api.uuni.cn/api/time', { method: 'POST' });
    data = (await res.json()) || {};
    console.log('======data======', data);
  } catch (error) {
    console.log('======error======', error);
  }

  // 获取请求的params URL 参数 对象格式
  const searchParams = Object.fromEntries(request.nextUrl.searchParams);
  console.log('======searchParams======', searchParams);

  // 获取请求的header信息 对象格式
  const headers = Object.fromEntries(request.headers);
  console.log('===========headers===========', headers);

  // 获取cookie信息 格式[ { name: 'name', value: 'test1' } ]
  const cookies = request.cookies.getAll();
  console.log('===========cookies===========', cookies);

  // 获取当前完整url
  const { url } = request;

  // 注: get请求没法用request.json()和request.formData()
  // 用request.json()和request.formData()这种异步的记得做错误处理,因为只有一没有对上匹配的数据格式就报错

  return NextResponse.json(
    // 设置返回参数
    {
      name: 'test-get',
      url,
      data,
      reqsearchParams: searchParams,
      reqheaders: headers,
      table1,
    },
    // 设置标头等
    {
      headers: {
        // status: '200',
        // 'Set-Cookie': 'name=test-get',
      },
    }
  );
}
